package xyz.zhouzhaodong.crm.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.zhouzhaodong.crm.entity.Staff;

import java.util.Date;

/**
 * JWT生成类
 * @author zhouzhaodong
 */
public class TokenUtil {

    private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    /**
     * 过期时间，暂定一天
     */
    private static final long EXPIRE_TIME= 24 * 60 * 60 * 1000;

    /**
     * 密钥盐
     */
    private static final String TOKEN_SECRET="CRMTOKEN";


    /**
     * 签名生成
     * @param staff
     * @return
     */
    public static String sign(Staff staff){

        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("auth0")
                    .withClaim("username", staff.getName())
                    .withClaim("password", staff.getPassword())
                    .withExpiresAt(expiresAt)
                    // 使用了HMAC256加密算法。
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e){
            e.printStackTrace();
        }
        return token;

    }


    /**
     * 签名验证
     * @param token
     * @return
     */
    public static boolean verify(String token){

        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
            logger.info("认证通过：");
            logger.info("issuer: " + jwt.getIssuer());
            logger.info("username: " + jwt.getClaim("username").asString());
            logger.info("password: " + jwt.getClaim("password").asString());
            // TODO 如果权限管理，可在此处添加校验
            logger.info("过期时间:" + jwt.getExpiresAt());
            return true;
        } catch (Exception e){
            return false;
        }

    }

}
